package com.expense.common.amiExt;

import com.expense.common.constant.enums.DeletedStatus;
import com.expense.common.model.base.BaseModel;
import org.beetl.sql.core.SQLManager;
import org.beetl.sql.core.mapper.MapperInvoke;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class SaveAllAmiExt implements MapperInvoke {

    public SaveAllAmiExt() {}

    @Override
    public Object call(SQLManager sqlManager, Class aClass, String s, Method method, Object[] objects) {
        if(objects[0] == null) return Boolean.FALSE;
        List<BaseModel> attrs = (List<BaseModel>) objects[0];
        if(attrs == null || attrs.size() == 0) return Boolean.FALSE;
        List<BaseModel> insertList = new ArrayList<>();
        List<BaseModel> updateList = new ArrayList<>();
        Map<Boolean,List<BaseModel>> partitioned = attrs.parallelStream().collect(Collectors.partitioningBy(t -> t == null || t.getId() == null || t.getId() <= 0));
        insertList = partitioned.get(Boolean.TRUE);
        updateList = partitioned.get(Boolean.FALSE);
        if(insertList != null && insertList.size() > 0) {
            insertList.parallelStream().forEach(m -> {
                m.setId(null);
                if(m.getDeleted() == null) m.setDeleted(DeletedStatus.UN_DELETED);
            });
            sqlManager.insertBatch(aClass,insertList);
        }
        if(updateList != null && updateList.size() > 0) sqlManager.updateBatchTemplateById(aClass,updateList);
        return Boolean.TRUE;
    }
}
